using System;
using Newtonsoft.Json;
using UnityEngine;

public class LocalData : MonoBehaviour
{
    
}

public interface ILocalData<T>
{
    T DefalutData();
}


public class LocalData<TModel,TData> : LocalData,ILocalData<TData>
{
    public static TModel Instance=>instance;
    private static TModel instance;
    [SerializeField]protected TData data;
    public event Action<int> EventUpdateDataCallBack;

    protected void UpdateCallBack(int p)
    {
        EventUpdateDataCallBack?.Invoke(p);
    }

    private void Awake()
    {
        AwakeInit();
    }

    public virtual void AwakeInit()
    {
        DontDestroyOnLoad(this.gameObject);
        instance = GetComponent<TModel>();
        InitData();
    }

    public void Save()
    {
        string content = JsonConvert.SerializeObject(data);
        PlayerPrefs.SetString(typeof(TModel).ToString(),content);
    }

    public void InitData()
    {
        string content = PlayerPrefs.GetString(typeof(TModel).ToString(), "");
        if (string.IsNullOrEmpty(content))
        {
            data = DefalutData();
        }
        else
        {
            data = JsonConvert.DeserializeObject<TData>(content);
        }
    }

    public virtual TData DefalutData()
    {
        return default(TData);
    }
}